<template>
  <div>
    <div style="padding-bottom: 20px; color: #0000FF;" @click="closePage">&lt;资讯</div>
    <div class="information_edit">
      <div class="page_top padding_20">发布资讯</div>
      <div class="page_content padding_20">
        <div class="content_title"><span>基本信息</span></div>
        <div class="page_content_tit">
          <span>封面</span><span class="must_icon">必填</span>
          <span style="font-size: 14px;color: #ccc;">720X720PX的图像最佳，大小请不要超过3M</span>
        </div>
        <div style="display: flex;">
          <el-upload
            class="avatar-uploader"
            accept="image/png,image/jpeg,image/gif"
            action="#"
            :show-file-list="false"
            :on-change="beforeAvatarUpload"
            :auto-upload="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>标题</span><span class="must_icon">必填</span></div>
          <el-input ref="title" v-model="title" placeholder="请输入内容" />
        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>所属品牌</span></div>
          <el-input v-model="brandval" readonly placeholder="kamisoul" />
        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>所属系列</span><span class="must_icon">必填</span></div>
          <el-select ref="seriesid" v-model="seriesid" placeholder="关联系列" style="width: 120px;">
            <el-option
              v-for="item in seriesoptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>模型类型</span><span class="must_icon">必填</span></div>
          <el-select ref="modeltypeid" v-model="modeltypeid" placeholder="模型类型" style="width: 120px;">
            <el-option
              v-for="(item,index) in modeloptions"
              :key="index"
              :label="item"
              :value="index"
            />
          </el-select>
        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>性别</span><span class="must_icon">必填</span></div>
          <el-radio-group v-model="sex">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </div>
        <div style="padding: 20px 0;">
          <div class="ad_item" style="align-items: center;"><span>上架时间</span><span class="must_icon">必填</span></div>
          <el-radio-group v-model="isupper">
            <el-radio :label="1">
              立即上架
            </el-radio>
            <el-radio :label="2">
              定时上架
              <el-date-picker
                v-model="shelftime"
                :disabled="isupper!==2"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                placeholder="选择日期时间"
              />
            </el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="page_content padding_20">
        <div class="content_title"><span>详细说明</span></div>
        <div><el-button type="primary" @click="detailsDraftAddAll">新增</el-button></div>
        <div v-for="(item,index) in detail" :key="index" class="detail_content">
          <div class="top_nav">
            <el-row>
              <el-col class="left" :span="6">
                <div>{{ item.addtime }} 更新</div>
              </el-col>
              <el-col class="right" :span="18">
                <div class="total_bar">
                  <el-button style="border: none;" @click="detailsDraftDelall(item.modelid,index)"><span>删除</span></el-button>
                  <i class="el-icon-caret-top" @click="detailsDraftMoveall(item.modelid,index,1)" />
                  <i class="el-icon-caret-bottom" @click="detailsDraftMoveall(item.modelid,index,2)" />
                </div>
              </el-col>

            </el-row>
          </div>
          <div class="detail_body">
            <div class="item">
              <div><span>标题</span></div>
              <el-radio-group v-model="item.titletype" @change="detailsDraftUpdateall(index)">
                <el-radio label="1" style="width: 50px;">
                  无
                </el-radio>
                <el-radio label="2">
                  <el-input v-model="item.title" :disabled="item.titletype!=='2'" placeholder="请输入内容" @change="detailsDraftUpdateall(index)" />
                </el-radio>
              </el-radio-group>
            </div>
            <div class="item">
              <div><span>出荷时间</span></div>
              <el-radio-group v-model="item.publishtype" @change="detailsDraftUpdateall(index)">
                <el-radio label="1" style="width: 50px;">
                  无
                </el-radio>
                <el-radio label="2">
                  <!-- <el-date-picker
                    v-model="item.publishtime2"
                    :disabled="item.publishtype!==2"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间"
                    @change="detailsDraftUpdateall(index)"
                  /> -->
                  <el-cascader
                    v-model="item.publishtime2"
                    :disabled="item.publishtype!=='2'"
                    separator=""
                    :props="{ expandTrigger: 'hover' }"
                    :options="publishtimeOptions"
                    @change="detailsDraftUpdateall(index)"
                  />
                </el-radio>
              </el-radio-group>
            </div>
            <div class="item">
              <div><span>定价</span></div>
              <el-radio-group v-model="item.moneytype" @change="detailsDraftUpdateall(index)">
                <el-radio label="1" style="width: 50px;">
                  未定
                </el-radio>
                <el-radio label="2">
                  <div style="display: inline-flex;align-items: center;justify-content: center;">
                    <el-input v-if="item.valuebi=='yen'" v-model="item.yen" style="flex:1;margin-right: 10px;" :disabled="item.moneytype!=='2'" placeholder="请输入内容" @change="detailsDraftUpdateall(index)" />
                    <el-input v-if="item.valuebi=='dollar'" v-model="item.dollar" style="flex:1;margin-right: 10px;" :disabled="item.moneytype!=='2'" placeholder="请输入内容" @change="detailsDraftUpdateall(index)" />
                    <el-select v-model="item.valuebi" placeholder="外币(选填)" style="width: 120px;" :disabled="item.moneytype!=='2'" @change="detailsDraftUpdateall(index)">
                      <el-option label="日元" value="yen" />
                      <el-option label="美元" value="dollar" />
                    </el-select>
                    <span style="margin: 0 10px;">=</span>
                    <el-input v-model="item.rmb" style="flex: 1;margin-right: 10px;" placeholder="请输入内容" :disabled="item.moneytype!=='2'" @change="detailsDraftUpdateall(index)" />
                    <span>人民币</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
            <div class="item">
              <div @mouseleave="detailsDraftUpdateall(index)">
                <tinymce :id="'tinymce'+index" v-model="item.content" :height="300" @onblur="detailsDraftUpdateall(index)" />
              </div>
            </div>

          </div>
        </div>
      </div>
      <div class="page_foot padding_20">
        <div>
          <el-button style="border-color: #409EFF;color: #409EFF;" @click="closePage">取消</el-button>
          <el-button type="primary" @click="informationAddall(2)">存入草稿</el-button>
          <el-button type="primary" @click="informationAddall(1)">发布</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import {
  detailsDraftClean, detailsDraftAdd, detailsDraftUpdate, detailsDraftDel,
  detailsDraftMove, getModelType, getSeriesList, informationAdd,
  informationDetail, detailsUpdate, detailsAdd, detailsDel, detailsMove, informationEdit,
  informationDetailInitialize
} from '@/api/information'
import tinymce from '@/components/Tinymce'
export default {
  components: { tinymce },
  props: {
    editdata: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
      },
      seriesoptions: [],
      modeloptions: [],
      seriesid: '',
      modeltypeid: '',
      sex: 0,
      isupper: 1,
      shelftime: '',
      brandid: '1',
      title: '',

      brandval: '',

      imageUrl: '',
      imgFile: '',

      detail: []
    }
  },
  computed: {
    // 出荷时间级联下拉
    publishtimeOptions() {
      const options = []
      // 子级
      const children = [{ value: 'Q0', label: '未定' }]
      for (let i = 1; i <= 4; i++) {
        children.push({ value: `Q${i}`, label: `Q${i}` })
      }
      for (let i = 1; i <= 12; i++) {
        children.push({ value: i + '', label: `${i}月` })
      }
      const date = new Date()
      const curYear = date.getFullYear() // 今年
      console.log('curYear', curYear)
      // 取10年前到明年
      for (let i = curYear - 13; i <= curYear + 1; i++) {
        const item = {
          value: i + '',
          label: `${i}年`,
          children
        }
        options.push(item)
      }
      console.log('options', options)
      return options.reverse()
    }
  },
  created() {
    console.log(this.editdata)
    if (this.editdata) {
      this.informationid = this.editdata.informationid
      this.informationDetailInitialize()
      this.informationDetail()
    } else {
      this.detailsDraftClean()
    }
    this.getModelType()
    this.getSeriesList()
  },
  methods: {
    beforeAvatarUpload(file) {
      console.log(file)
      this.imgFile = file.raw
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    closePage() {
      this.$parent.closeEditpage()
      this.$router.push('/information/information') // 清除query data
    },
    detailsDraftClean() {
      detailsDraftClean().then()
    },
    informationDetailInitialize() {
      informationDetailInitialize({ informationid: this.informationid }).then()
    },
    detailsDraftAddAll() {
      if (this.editdata) {
        this.detailsAdd()
      } else {
        this.detailsDraftAdd()
      }
    },
    detailsDraftAdd() {
      detailsDraftAdd().then(response => {
        this.detail.unshift({
          'modelid': response.detail.modelid,
          'titletype': '1',
          'title': '',
          'publishtype': '1',
          'publishyear': '',
          'publishtime': '',
          'moneytype': '1',
          'yen': '0',
          'dollar': '0',
          'rmb': '0',
          'content': '',
          'sortid': response.detail.sortid,
          valuebi: ''
        })
      })
    },
    detailsAdd() {
      detailsAdd({ informationid: this.informationid }).then(response => {
        this.detail.unshift({
          'modelid': response.detail.modelid,
          'titletype': '1',
          'title': '',
          'publishtype': '1',
          'publishyear': '',
          'publishtime': '',
          'moneytype': '1',
          'yen': '0',
          'dollar': '0',
          'rmb': '0',
          'content': '',
          'sortid': response.detail.sortid,
          valuebi: ''
        })
      })
    },
    detailsDraftUpdateall(index) {
      if (this.editdata) {
        this.detailsUpdate(index)
      } else {
        this.detailsDraftUpdate(index)
      }
    },
    detailsDraftUpdate(index) {
      console.log('this.detail[index].publishtime2', this.detail[index].publishtime2)
      if (this.detail[index].publishtime2) {
        // this.detail[index].publishyear = this.detail[index].publishtime2.split(' ')[0]
        this.detail[index].publishyear = this.detail[index].publishtime2[0]
        // this.detail[index].publishtime = this.detail[index].publishtime2.split(' ')[1]
        this.detail[index].publishtime = this.detail[index].publishtime2[1]
      }
      if (this.detail[index].valuebi === 'yen') {
        this.detail[index].dollar = 0
      } else {
        this.detail[index].yen = 0
      }
      detailsDraftUpdate(this.detail[index]).then(response => {

      })
    },
    detailsUpdate(index) {
      if (this.detail[index].publishtime2) {
        // this.detail[index].publishyear = this.detail[index].publishtime2.split(' ')[0]
        this.detail[index].publishyear = this.detail[index].publishtime2[0]
        // this.detail[index].publishtime = this.detail[index].publishtime2.split(' ')[1]
        this.detail[index].publishtime = this.detail[index].publishtime2[1]
      }
      if (this.detail[index].valuebi === 'yen') {
        this.detail[index].dollar = 0
      } else {
        this.detail[index].yen = 0
      }
      detailsUpdate(this.detail[index]).then(response => {

      })
    },
    detailsDraftDelall(modelid, index) {
      if (this.editdata) {
        this.detailsDel(modelid, index)
      } else {
        this.detailsDraftDel(modelid, index)
      }
    },
    detailsDraftDel(modelid, index) {
      this.$confirm('此操作将删除该模块, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detailsDraftDel({ 'modelid': modelid }).then(response => {
          this.detail.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    detailsDel(modelid, index) {
      this.$confirm('此操作将删除该模块, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detailsDel({ 'modelid': modelid, informationid: this.informationid }).then(response => {
          this.detail.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    detailsDraftMoveall(modelid, index, status) {
      if (this.editdata) {
        this.detailsMove(modelid, index, status)
      } else {
        this.detailsDraftMove(modelid, index, status)
      }
    },
    detailsDraftMove(modelid, index, status) {
      detailsDraftMove({ modelid: modelid, status: status }).then(res => {
        if (res.detail.length !== 0) {
          console.log(res)
          if (status === 1) {
            this.detail.splice(index, 1, ...this.detail.splice(index - 1, 1, this.detail[index]))
          } else {
            this.detail.splice(index, 1, ...this.detail.splice(index + 1, 1, this.detail[index]))
          }
        }
      })
    },
    detailsMove(modelid, index, status) {
      detailsMove({ modelid: modelid, status: status, informationid: this.informationid }).then(res => {
        if (res.detail.length !== 0) {
          console.log(res)
          if (status === 1) {
            this.detail.splice(index, 1, ...this.detail.splice(index - 1, 1, this.detail[index]))
          } else {
            this.detail.splice(index, 1, ...this.detail.splice(index + 1, 1, this.detail[index]))
          }
        }
      })
    },
    getSeriesList() {
      getSeriesList().then(res => {
        this.seriesoptions = res.detail.data
      })
    },
    getModelType() {
      getModelType().then(res => {
        this.modeloptions = res.detail.data
      })
    },
    // 校验必填参数
    checkParams() {
      // 关联资讯
      if(!this.imgFile && !this.imageUrl) {
        this.$message.error('请添加封面')
        return false
      } else if(!this.title) {        
        this.$message.error('请输入标题')
        this.$refs.title && this.$refs.title.focus()
        return false
      } else if(!this.seriesid) {
        this.$refs.seriesid && this.$refs.seriesid.focus()
        this.$message.error('请选择所属系列')
        return false
      } else if(!this.modeltypeid) {
        this.$refs.modeltypeid && this.$refs.modeltypeid.focus()
        this.$message.error('请选择模型系列')
        return false
      } else {
        return true
      }
    },
    informationAddall(type) {
      if(!this.checkParams()) return
      if (this.editdata) {
        this.informationEdit(type)
      } else {
        this.informationAdd(type)
      }
    },
    informationAdd(type) {
      const self = this
      informationAdd({
        frames: 1,
        title: self.title,
        brandid: self.brandid,
        seriesid: self.seriesid,
        modeltypeid: self.modeltypeid,
        sex: self.sex,
        isupper: self.isupper,
        shelftime: self.shelftime,
        type: type,
        files: self.imgFile
      }).then(response => {
        self.$message({
          message: '操作成功',
          type: 'success'
        })
        self.closePage()
        this.$parent.getData()
      })
    },
    informationEdit(type) {
      const self = this
      informationEdit({
        informationid: this.informationid,
        frames: 1,
        title: self.title,
        brandid: self.brandid,
        seriesid: self.seriesid,
        modeltypeid: self.modeltypeid,
        sex: self.sex,
        isupper: self.isupper,
        shelftime: self.shelftime,
        type: type,
        files: self.imgFile
      }).then(response => {
        self.$message({
          message: '操作成功',
          type: 'success'
        })
        self.closePage()
        this.$parent.getData()
      })
    },
    informationDetail() {
      informationDetail({ informationid: this.informationid }).then(res => {
        this.seriesid = res.detail.seriesid
        this.modeltypeid = Number(res.detail.modeltypeid)
        this.sex = Number(res.detail.sex)
        this.isupper = Number(res.detail.isupper)
        this.shelftime = res.detail.shelftime
        this.brandid = Number(res.detail.brandid)
        this.title = res.detail.title
        this.imageUrl = res.detail.img
        this.detail = res.detail.list
        this.detail.forEach(item => {
          console.log([item.publishyear, item.publishtime])
          this.$set(item, 'publishtime2', [item.publishyear, item.publishtime])
          this.$set(item, 'valuebi', parseFloat(item.yen) > 0 ? 'yen' : parseFloat(item.dollar) > 0 ? 'dollar' : '')
        })
      })
    }
  }
}
</script>
<style>
	.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style lang="less" scoped>
.padding_20{
	padding: 20px;
}
.must_icon{
	color: #fff;
	background: #FF4D51;
	padding: 4px;
	font-size: 12px;
}

.information_edit{
	border: 1px solid #ccc;
	background: #fff;
}

.page_top{
	font-size: 16px;
	font-weight: 600;
	border-bottom: 1px solid #ccc;
}
.page_content{
	border-bottom: 1px solid #ccc;
	.detail_content{
		.top_nav{
			margin: 10px 0 20px 0;
			.left{
				font-size: 14px;
				color: #ccc;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 1px solid #ccc;
				border-bottom: none;
			}
			.right{
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				border-bottom: 1px solid #ccc;
			}
		}
		.detail_body{
			padding-left: 10px;
			.item{
				margin: 10px 0;
			}
		}
	}
}
.content_title{
	font-size: 16px;
	font-weight: 600;
	padding-bottom: 10px;
}
.page_content_tit{
	padding-bottom: 10px;
	display: flex;
	align-items: center;
}
.page_foot{
	display: flex;
	justify-content: flex-end;
}
.ad_item{
	display: flex;
	margin-bottom: 10px;
}

</style>
